package com.scrx.ymg.dao.orderform;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.scrx.ymg.dao.base.BaseDaoImpl;
import com.scrx.ymg.entity.AgentMoney;
import com.scrx.ymg.entity.DirectProduct;
import com.scrx.ymg.entity.HeadMoney;
import com.scrx.ymg.entity.OrderForm;
import com.scrx.ymg.entity.OrderFormDetails;
import com.scrx.ymg.entity.OrderReturn;
import com.scrx.ymg.entity.OtherMoney;
import com.scrx.ymg.entity.ProductEvaluate;
import com.scrx.ymg.entity.SeckillProduct;
import com.scrx.ymg.entity.SuperMarketEntrepot;
import com.scrx.ymg.entity.SupermarketMoney;
import com.scrx.ymg.entity.SupermarketSet;
import com.scrx.ymg.entity.User;
import com.scrx.ymg.entity.UserComplain;
import com.scrx.ymg.util.LatLonUtil;
import com.scrx.ymg.util.WeixinUtil;

@Repository("orderFormDao")
@Transactional(rollbackFor={Exception.class})
public class OrderFormDaoImpl extends BaseDaoImpl implements IOrderFormDao {
	
	private static final Logger log = LoggerFactory.getLogger(OrderFormDaoImpl.class);

	
	public void save(OrderForm transientInstance) {
        log.debug("saving OrderForm instance");
        try {
            getCurrentSession().save(transientInstance);
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }
	public String update(OrderForm orderForm) {
        log.debug("update OrderForm instance");
        String isOK="false";
        try {
            getCurrentSession().update(orderForm);
            log.debug("update successful");
            isOK="true";
        } catch (RuntimeException re) {
            log.error("update failed", re);
            throw re;
        }
        return isOK;
    }
	public String saveOrderFormAndDetails(User user,OrderForm order,List<OrderFormDetails> details,List<SuperMarketEntrepot> superEns) {
        log.debug("saving OrderForm And Details instance");
        String temp="false";
        try {
        	
            getCurrentSession().save(order);
            for (int i = 0; i < details.size(); i++) {
				OrderFormDetails detail=details.get(i);
				detail.setOrderDetailsId(order.getOrderFormId()+(i+1));
				detail.setOrderFormId(order.getOrderFormId());
				detail.setStatus(1);
				detail.setOrderId(order.getId());
				getCurrentSession().save(detail);
			}
            for (SuperMarketEntrepot superMarketEntrepot : superEns) {
            	getCurrentSession().update(superMarketEntrepot);
			}
            getCurrentSession().update(user);
            log.debug("save successful");
            return "true";
           
        } catch (Exception re) {
            log.error("save failed", re);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            re.printStackTrace();
            return "false";

        }
    }
	
	
	public List<OrderForm> getOrderFormGroupStatus(String userId) {
		try {
			Query query=getCurrentSession().createQuery("select status,count(id) as num from OrderForm where userId=:id  group by status");
			query.setParameter("id", Integer.parseInt(userId));
            return query.list();
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
		
	}

	public List<OrderForm> getOrderFormByStatus(String userid, String status) {
		try {
			String hql="from OrderForm where userId=:userId and status=:status ";
			if(status.equals("5")){
				hql="from OrderForm where userId=:userId and status in(:status,6,7) ";
			}
			Query query=getCurrentSession().createQuery(hql);
			
			query.setParameter("userId", Integer.parseInt(userid));
			query.setParameter("status", Integer.parseInt(status));
			List<OrderForm> oflist=query.list();
			for (OrderForm orderForm : oflist) {
				Query query2=getCurrentSession().createQuery("from OrderFormDetails where orderFormId=:id");
				query2.setParameter("id", orderForm.getOrderFormId());
				orderForm.setOrderFormDetails(query2.list());
			}
            return oflist;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
	}

	public List<OrderForm> getOrderFormByUserID(String userid) {
		try {
			Query query=getCurrentSession().createQuery("from OrderForm where userId=:userId and status not in(0,8)");
			query.setParameter("userId", Integer.parseInt(userid));
			List<OrderForm> oflist=query.list();
			for (OrderForm orderForm : oflist) {
				Query query2=getCurrentSession().createQuery("from OrderFormDetails where orderFormId=:id");
				query2.setParameter("id", orderForm.getOrderFormId());
				orderForm.setOrderFormDetails(query2.list());
			}
            return oflist;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
	}

	
	public OrderForm getOrderFormByOrderFormID(String orderFormID) {
		try {
			Query query=getCurrentSession().createQuery("from OrderForm where orderFormId=:id ");
			query.setParameter("id", orderFormID);
			OrderForm oflist=(OrderForm)query.uniqueResult();
            return oflist;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
	}

	public String takeDeliveryOfGoods(OrderForm order, SupermarketMoney money,User user) {
		try {
			 getCurrentSession().update(order);
			 getCurrentSession().update(money);
			 getCurrentSession().update(user);
			 return "true";
        } catch (RuntimeException re) {
            log.error("get failed", re);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "false";
        }
		
	}

	public List<OrderForm> getOrderFormBySuperID(String superID, String status) {
		try {
			Query query=getCurrentSession().createQuery("from OrderForm where superId=:superId and status=:status and typeId=1");
			query.setParameter("superId", Integer.parseInt(superID));
			query.setParameter("status", Integer.parseInt(status));
			List<OrderForm> oflist=query.list();
			for (OrderForm orderForm : oflist) {
				Query query2=getCurrentSession().createQuery("from OrderFormDetails where orderFormId=:id");
				query2.setParameter("id", orderForm.getOrderFormId());
				orderForm.setOrderFormDetails(query2.list());
			}
            return oflist;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
	}

	public Map<Object, Object> getOrderFormBySuper(OrderForm orderform,String startTime,String endTime,int pageNum,int pageCount) {
		try {
			LatLonUtil util=new LatLonUtil();
			String username=null;
			if(orderform.getUserName()!=null){
				username=orderform.getUserName().trim();
			}
			String phone=null;
			if(orderform.getPhone()!=null){
				phone=orderform.getPhone().trim();
			}
			
			StringBuffer hql =new StringBuffer("from OrderForm where 1=1 ");
			util.initStartDateTime(startTime, "orderFormTime", hql);
			util.initEndDateTime(endTime, "orderFormTime", hql);
			init(orderform.getSuperId(),"superId",hql);
			util.initStatus(orderform.getStatus(),"status",hql);
			init(username,"userName", hql);
			init(phone,"phone",hql);
			init(orderform.getCode(),"code",hql);
			init(orderform.getPaymentType(),"paymentType",hql);
			init(orderform.getOrderFormId(),"orderFormId",hql);
			init(orderform.getTypeId(),"typeId",hql);
			hql.append(" and status not in(-1,0)  order by orderFormTime");
			Query query=getCurrentSession().createQuery(hql.toString());
			query.setMaxResults(pageCount);//每页多少条
			query.setFirstResult((pageNum-1)*pageCount);//第几页
			List<OrderForm> orderlist=query.list();
			for (OrderForm orderForm : orderlist) {
				Query query2=getCurrentSession().createQuery("from OrderFormDetails where orderFormId=:id");
				query2.setParameter("id", orderForm.getOrderFormId());
				orderForm.setOrderFormDetails(query2.list());
			}
			Query totalpage=getCurrentSession().createQuery(hql.toString());	
			Map<Object, Object> map = new HashMap<Object, Object>();
			map.put("orderlist", orderlist);
			map.put("totalpage", (totalpage.list().size()+pageCount-1)/pageCount);
            return map;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
	}
	public Map<Object, Object> getOrderFormBySuper(OrderForm orderform,int pageNum,int pageCount) {
		try {
			String username=null;
			if(orderform.getUserName()!=null){
				username=orderform.getUserName().trim();
			}
			String phone=null;
			if(orderform.getPhone()!=null){
				phone=orderform.getPhone().trim();
			}
			StringBuffer hql =new StringBuffer("from OrderForm where 1=1 ");
			init(orderform.getSuperId(),"superId",hql);
			init(orderform.getStatus(),"status",hql);
			init(username,"userName", hql);
			init(phone,"phone",hql);
			init(orderform.getTypeId(),"typeId",hql);
			init(orderform.getPaymentType(),"paymentType",hql);
			init(orderform.getOrderFormId(),"orderFormId",hql);
			hql.append(" and status!=0  order by orderFormTime");
			Query query=getCurrentSession().createQuery(hql.toString());
			query.setMaxResults(pageCount);//每页多少条
			query.setFirstResult((pageNum-1)*pageCount);//第几页
			List<OrderForm> orderlist=query.list();
			for (OrderForm orderForm : orderlist) {
				Query query2=getCurrentSession().createQuery("from OrderFormDetails where orderFormId=:id");
				query2.setParameter("id", orderForm.getOrderFormId());
				orderForm.setOrderFormDetails(query2.list());
			}
			Query totalpage=getCurrentSession().createQuery(hql.toString());	
			Map<Object, Object> map = new HashMap<Object, Object>();
			map.put("orderlist", orderlist);
			map.put("totalpage", (totalpage.list().size()+pageCount-1)/pageCount);
            return map;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
	}
	  public void init(Object obj,Object obj2,StringBuffer hql){
		  if(obj2.equals("userName")&&obj!=null&obj!=""){
			  hql.append(" and "+obj2+" like '%"+obj+"%'");
		  }else if(obj!=null&&obj!=""){
				hql.append(" and "+obj2+"='"+obj+"'");
		  }
	  }
	public List<SuperMarketEntrepot> getSuperMarketEntrepotes(List<OrderFormDetails> details) {
		try {
			List<SuperMarketEntrepot> smets= new ArrayList<SuperMarketEntrepot>();
			for (OrderFormDetails ofds : details) {
				Query query2=getCurrentSession().createQuery("from SuperMarketEntrepot where id=:id");
				query2.setParameter("id", ofds.getProductId());
				SuperMarketEntrepot sme=(SuperMarketEntrepot)query2.uniqueResult();
				if(sme!=null){
				smets.add(sme);
				}
			}
            return smets;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
		       
	}
	public List<DirectProduct> getDirectProductByOrderFormDetails(List<OrderFormDetails> details) {
		try {
			List<DirectProduct> smets= new ArrayList<DirectProduct>();
			for (OrderFormDetails ofds : details) {
				Query query2=getCurrentSession().createQuery("from DirectProduct where id=:id");
				query2.setParameter("id", ofds.getDirectId());
				DirectProduct sme=(DirectProduct)query2.uniqueResult();
				if(sme!=null){
				smets.add(sme);
				}
			}
            return smets;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
		       
	}

	public OrderForm getOrderFormByID(int ID) {
			try {
				Query query=getCurrentSession().createQuery("from OrderForm where id=:id ");
				query.setParameter("id", ID);
				OrderForm oflist=(OrderForm)query.uniqueResult();
	            return oflist;
	        } catch (RuntimeException re) {
	            log.error("get failed", re);
	            throw re;
	        }
	}

	public String complaintOrderForm(OrderForm order, UserComplain com) {
		String temp="false";
		try {
			getCurrentSession().update(order);
			getCurrentSession().save(com);
			temp= "true";
        } catch (RuntimeException re) {
            log.error("get failed", re);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "false";
        }
		return temp;
	}

	public String evaluateOrderForm(OrderForm order,List<ProductEvaluate> pevalist) {
		try {
			getCurrentSession().update(order);
			for (ProductEvaluate productEvaluate : pevalist) {
				getCurrentSession().save(productEvaluate);
			}
            return "true";
        } catch (RuntimeException re) {
            log.error("get failed", re);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "false";
        }
	}

	public String getSendPhone(int superID) { 
		try {
			Query query=getCurrentSession().createQuery("from SupermarketSet where supermarketId=:id ");
			query.setParameter("id", superID);
			SupermarketSet user=(SupermarketSet)query.uniqueResult();
			if(user!=null){
				 return user.getSendPhone();
			}
           return "false";
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
	}

	public Map<Object, Object> getUserReturn(OrderReturn order,int pageCount,int pageNum) {
		try {
			StringBuffer hql =new StringBuffer("from OrderReturn where 1=1 ");
			int i=0;
			init(order.getShopId(),"shopId",hql);
			init(order.getStatus(),"status", hql);
			init(order.getUserName(),"userName", hql);
			init(order.getUserPhone(),"userPhone",hql);
			init(order.getOrderFromId(),"orderFromId",hql);
			init(order.getOrderType(),"orderType",hql);
			hql.append(" order by returnTime");
			Query query=getCurrentSession().createQuery(hql.toString());
			query.setMaxResults(pageCount);//每页多少条
			query.setFirstResult((pageNum-1)*pageCount);//第几页
			List<OrderReturn> returnlist=query.list();
			List<OrderForm> orderlist=new ArrayList<OrderForm>();
			//查询订单
			for (OrderReturn orderRetrun : returnlist) {
				Query query2=getCurrentSession().createQuery("from OrderForm where orderFormId=:id");
				query2.setParameter("id", orderRetrun.getOrderFromId());
				OrderForm orderform=(OrderForm)query2.uniqueResult();
				orderform.setOreturn(orderRetrun);
				orderlist.add(orderform);
			}
			Query totalpage=getCurrentSession().createQuery(hql.toString());
			Map<Object, Object> map = new HashMap<Object, Object>();
			map.put("orderlist", orderlist);
			map.put("totalpage", totalpage.list().size());
            return map;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
	}
	
	public OrderReturn getOrderReturnByorderID(String orderFormId){
		Query query=getCurrentSession().createQuery("from OrderReturn where orderFromId=:id");
		query.setParameter("id", orderFormId);
		return (OrderReturn)query.uniqueResult();
	}

	
	public String setOrderFormAndOrderReturn(OrderForm order,Object headMoney,List<SuperMarketEntrepot> entrlist) {
		try {
			getCurrentSession().update(order);
			if(headMoney!=null){
				getCurrentSession().update(headMoney);
			}
			if(entrlist!=null){
				for (SuperMarketEntrepot entrepot : entrlist) {
					getCurrentSession().update(entrepot);
				}
			}
			
			return "true";
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "false";
		}
		
		
		
	}

	public List<OrderFormDetails> getOrderFormDetailsByOrderFormID(String orderFormId) {
		Query query=getCurrentSession().createQuery("from OrderFormDetails where orderFormId=:id");
		query.setParameter("id", orderFormId);
		return (List<OrderFormDetails>)query.list();
	}
	


	public String updateObjects(OrderForm oldorder, Object otherMoney, SupermarketMoney superMoney,
			AgentMoney agentMoney, HeadMoney headMoney) {
		try {
			getCurrentSession().update(oldorder);
			getCurrentSession().update(otherMoney);
			if(superMoney!=null){
				getCurrentSession().update(superMoney);
			}
			if(agentMoney!=null){
				getCurrentSession().update(agentMoney);
			}
			getCurrentSession().update(headMoney);
			return "true";
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "false";
		}
	}
	public String updateOrderFormAndHeadMoney(OrderForm order, HeadMoney headMoney) {
		try {
			getCurrentSession().update(order);
			getCurrentSession().update(headMoney);
			return "true";
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "false";
		}
	}

	public String updateOrderFormAndHeadMoney(OrderForm order, HeadMoney headMoney,SeckillProduct product) {
		try {
			getCurrentSession().update(order);
			getCurrentSession().update(headMoney);
			if(product!=null){
				getCurrentSession().update(product);
			}
			return "true";
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "false";
		}
	}

	public String updateByAd(SeckillProduct oldproduct, AgentMoney agentMoney, HeadMoney headMoney) {
		try {
			getCurrentSession().update(oldproduct);
			getCurrentSession().update(headMoney);
			getCurrentSession().update(agentMoney);
			return "true";
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "false";
		}
	}

	public String update(OrderForm order, List<SuperMarketEntrepot> entrlist) {
		try {
			getCurrentSession().update(order);
            for (SuperMarketEntrepot entrepot : entrlist) {
            	getCurrentSession().update(entrepot);
			}
			return "true";
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "false";
		}
	}

	public List<OrderForm> getOrderFormList(OrderForm order) {
		LatLonUtil util=new LatLonUtil();
		StringBuffer hql =new StringBuffer("from OrderForm where 1=1 ");
		init(order.getStatus(),"status", hql);
		init(order.getPaymentType(),"paymentType", hql);
		init(order.getTypeId(),"typeId", hql);
		util.initEndDateTime(order.getOrderFormTime(), "orderFormTime", hql);
		hql.append(" order by orderFormTime");
		Query query=getCurrentSession().createQuery(hql.toString());
	return query.list();	
	}

	
	public void saveOrderFormList(List<OrderForm> list) {
		try {
			for (OrderForm orderForm : list) {
				this.getCurrentSession().save(orderForm);
			}
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		}
	}

	public String saveOrderFormListAndDetails(User user, OrderForm payorder, List<OrderForm> orderlist,
			List<DirectProduct> products) {
		  log.debug("saving OrderForm And Details instance");
	        String temp="false";
	        try {
	            getCurrentSession().save(payorder);
	            for (int i = 0; i < orderlist.size(); i++) {
	            	OrderForm order=orderlist.get(i);
	            	order.setParent(payorder.getId());
	            	getCurrentSession().save(order);
					OrderFormDetails detail=order.getOrderFormDetails().get(0);
					detail.setOrderId(order.getId());
					getCurrentSession().save(detail);
				}
	            for (DirectProduct product : products) {
	            	getCurrentSession().update(product);
				}
	            getCurrentSession().update(user);
	            log.debug("save successful");
	            return "true";
	        } catch (Exception re) {
	            log.error("save failed", re);
	            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	            re.printStackTrace();
	            return "false";

	        }
	}

	public List<OrderForm> getOrderFormListByPreant(Integer parent) {
		Query query=getCurrentSession().createQuery("from OrderForm where parent=:parent");
		query.setParameter("parent", parent);
		return (List<OrderForm>)query.list();
	}

	public String updateOrderFormAndHeadMoney(OrderForm order, HeadMoney headMoney, List<OrderForm> list) {
		try {
			getCurrentSession().update(order);
			getCurrentSession().update(headMoney);
			for (int i = 0; i < list.size(); i++) {
				getCurrentSession().update(list.get(i));
			}
			return "true";
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			e.printStackTrace();
            return "false";
		}
	}

	public String updateOrderFormSendMessage(OrderForm order, List<OrderForm> list) {
		try {
			getCurrentSession().update(order);
			for (int i = 0; i < list.size(); i++) {
				getCurrentSession().update(list.get(i));
			}
			return "true";
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			e.printStackTrace();
            return "false";
		}
	}
	@Override
	public String insertPurchaseOrder(User user, OrderForm order, List<DirectProduct> products) {
		  log.debug("saving OrderForm And Details instance");
	        String temp="false";
	        try {
	            getCurrentSession().save(order);
	            for (int i = 0; i < order.getOrderFormDetails().size(); i++) {
					OrderFormDetails detail=order.getOrderFormDetails().get(i);
					detail.setOrderId(order.getId());
					getCurrentSession().save(detail);
				}
	            for (DirectProduct product : products) {
	            	getCurrentSession().update(product);
				}
	            getCurrentSession().update(user);
	            log.debug("save successful");
	            return "true";
	        } catch (Exception re) {
	            log.error("save failed", re);
	            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	            re.printStackTrace();
	            return "false";

	        }
	}

}
